const cloud = require('wx-server-sdk')
const ExcelJS = require('exceljs')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

/**
 * 数据导出云函数主入口
 */
exports.main = async (event, context) => {
  const { action } = event

  try {
    switch (action) {
      case 'getStatistics':
        return await getActivityStatistics(event, context)
      case 'exportExcel':
        return await exportActivityDataToExcel(event, context)
      default:
        return {
          success: false,
          message: '不支持的操作'
        }
    }
  } catch (error) {
    console.error('数据导出云函数错误:', error)
    return {
      success: false,
      message: '服务器错误',
      error: error.message
    }
  }
}

/**
 * 获取活动统计数据
 */
async function getActivityStatistics(event, context) {
  const { activityId } = event

  if (!activityId) {
    return {
      success: false,
      message: '活动ID不能为空'
    }
  }

  try {
    // 获取活动基本信息
    const activityResult = await db.collection('activities').doc(activityId).get()
    if (!activityResult.data) {
      return {
        success: false,
        message: '活动不存在'
      }
    }

    const activity = activityResult.data

    // 获取该活动的所有候选人
    const candidatesResult = await db.collection('candidates')
      .where({
        activityId: activityId,
        status: 'active'
      })
      .orderBy('votes', 'desc')
      .get()

    const candidates = candidatesResult.data || []

    // 计算统计数据
    const totalVotes = candidates.reduce((sum, candidate) => sum + (candidate.votes || 0), 0)
    const participantCount = candidates.length

    // 计算每个候选人的投票百分比
    const candidatesWithPercent = candidates.map(candidate => {
      const percent = totalVotes > 0 ? Math.round((candidate.votes / totalVotes) * 100) : 0
      return {
        ...candidate,
        percent: percent,
        imageUrl: candidate.images && candidate.images.length > 0 ? candidate.images[0] : ''
      }
    })

    // 模拟浏览量（实际项目中应该有专门的访问记录表）
    const viewCount = Math.max(totalVotes * 2, participantCount * 10)

    // 格式化活动时间
    let timeRange = '未设置'
    if (activity.startTime && activity.endTime) {
      const startDate = new Date(activity.startTime).toLocaleDateString()
      const endDate = new Date(activity.endTime).toLocaleDateString()
      timeRange = `${startDate} - ${endDate}`
    }

    // 确定活动状态
    let statusText = '未知'
    const now = new Date()
    if (activity.status === 'draft') {
      statusText = '草稿'
    } else if (activity.status === 'ended') {
      statusText = '已结束'
    } else if (activity.status === 'paused') {
      statusText = '已暂停'
    } else if (activity.endTime && new Date(activity.endTime) < now) {
      statusText = '已结束'
    } else if (activity.startTime && new Date(activity.startTime) <= now) {
      statusText = '进行中'
    } else {
      statusText = '未开始'
    }

    return {
      success: true,
      data: {
        activity: {
          id: activityId,
          title: activity.title || '未命名活动',
          description: activity.description || '',
          timeRange: timeRange,
          statusText: statusText,
          participantCount: participantCount,
          totalVotes: totalVotes,
          viewCount: viewCount
        },
        candidates: candidatesWithPercent
      }
    }
  } catch (error) {
    console.error('获取活动统计数据失败:', error)
    return {
      success: false,
      message: '获取统计数据失败',
      error: error.message
    }
  }
}

/**
 * 导出活动数据到Excel
 */
async function exportActivityDataToExcel(event, context) {
  const { activityId } = event

  if (!activityId) {
    return {
      success: false,
      message: '活动ID不能为空'
    }
  }

  try {
    // 获取统计数据
    const statsResult = await getActivityStatistics({ activityId }, context)
    if (!statsResult.success) {
      return statsResult
    }

    const { activity, candidates } = statsResult.data

    // 创建Excel工作簿
    const workbook = new ExcelJS.Workbook()
    
    // 设置工作簿属性
    workbook.creator = 'qlzy投票系统'
    workbook.created = new Date()
    workbook.modified = new Date()

    // 创建工作表
    const worksheet = workbook.addWorksheet('投票数据统计')

    // 设置列宽
    worksheet.columns = [
      { header: '序号', key: 'rank', width: 8 },
      { header: '候选人姓名', key: 'name', width: 20 },
      { header: '票数', key: 'votes', width: 12 },
      { header: '得票率', key: 'percent', width: 12 },
      { header: '描述', key: 'description', width: 30 }
    ]

    // 添加标题行
    worksheet.addRow({})
    const titleRow = worksheet.addRow({
      rank: `${activity.title} - 投票统计报告`
    })
    worksheet.mergeCells('A2:E2')
    titleRow.getCell(1).font = { bold: true, size: 16 }
    titleRow.getCell(1).alignment = { horizontal: 'center' }

    // 添加活动信息
    worksheet.addRow({})
    worksheet.addRow({ rank: '活动信息', name: '', votes: '', percent: '', description: '' })
    worksheet.addRow({ rank: '活动名称:', name: activity.title })
    worksheet.addRow({ rank: '活动时间:', name: activity.timeRange })
    worksheet.addRow({ rank: '活动状态:', name: activity.statusText })
    worksheet.addRow({ rank: '参与人数:', name: activity.participantCount })
    worksheet.addRow({ rank: '总投票数:', name: activity.totalVotes })
    worksheet.addRow({ rank: '总浏览量:', name: activity.viewCount })

    // 添加空行
    worksheet.addRow({})

    // 添加候选人数据标题
    const headerRow = worksheet.addRow({
      rank: '排名',
      name: '候选人姓名',
      votes: '票数',
      percent: '得票率(%)',
      description: '描述'
    })

    // 设置标题行样式
    headerRow.eachCell((cell) => {
      cell.font = { bold: true }
      cell.fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'FFE0E0E0' }
      }
      cell.border = {
        top: { style: 'thin' },
        left: { style: 'thin' },
        bottom: { style: 'thin' },
        right: { style: 'thin' }
      }
      cell.alignment = { horizontal: 'center' }
    })

    // 添加候选人数据
    candidates.forEach((candidate, index) => {
      const row = worksheet.addRow({
        rank: index + 1,
        name: candidate.name,
        votes: candidate.votes || 0,
        percent: candidate.percent || 0,
        description: candidate.description || ''
      })

      // 设置数据行样式
      row.eachCell((cell, colNumber) => {
        cell.border = {
          top: { style: 'thin' },
          left: { style: 'thin' },
          bottom: { style: 'thin' },
          right: { style: 'thin' }
        }
        
        if (colNumber === 1 || colNumber === 3 || colNumber === 4) {
          cell.alignment = { horizontal: 'center' }
        }
      })

      // 为前三名添加特殊颜色
      if (index < 3) {
        const colors = ['FFFFD700', 'FFC0C0C0', 'FFCD7F32'] // 金、银、铜
        row.getCell(1).fill = {
          type: 'pattern',
          pattern: 'solid',
          fgColor: { argb: colors[index] }
        }
      }
    })

    // 添加总结行
    worksheet.addRow({})
    const summaryRow = worksheet.addRow({
      rank: '总计',
      name: `${candidates.length}位候选人`,
      votes: activity.totalVotes,
      percent: '100%',
      description: `报告生成时间: ${new Date().toLocaleString()}`
    })

    summaryRow.eachCell((cell) => {
      cell.font = { bold: true }
      cell.fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'FFF0F8FF' }
      }
      cell.border = {
        top: { style: 'thin' },
        left: { style: 'thin' },
        bottom: { style: 'thin' },
        right: { style: 'thin' }
      }
    })

    // 生成Excel文件buffer
    const buffer = await workbook.xlsx.writeBuffer()

    // 生成文件名
    const fileName = `${activity.title}_投票统计_${new Date().toISOString().split('T')[0]}.xlsx`
    const cloudPath = `exports/${activityId}/${fileName}`

    // 上传到云存储
    const uploadResult = await cloud.uploadFile({
      cloudPath: cloudPath,
      fileContent: buffer
    })

    if (uploadResult.fileID) {
      // 获取临时下载链接
      const tempUrlResult = await cloud.getTempFileURL({
        fileList: [uploadResult.fileID]
      })

      if (tempUrlResult.fileList && tempUrlResult.fileList[0] && tempUrlResult.fileList[0].status === 0) {
        return {
          success: true,
          data: {
            fileID: uploadResult.fileID,
            fileName: fileName,
            downloadUrl: tempUrlResult.fileList[0].tempFileURL,
            cloudPath: cloudPath,
            fileSize: buffer.length,
            statistics: {
              activityTitle: activity.title,
              participantCount: activity.participantCount,
              totalVotes: activity.totalVotes,
              viewCount: activity.viewCount,
              candidateCount: candidates.length
            }
          }
        }
      } else {
        throw new Error('获取下载链接失败')
      }
    } else {
      throw new Error('文件上传失败')
    }
  } catch (error) {
    console.error('导出Excel失败:', error)
    return {
      success: false,
      message: '导出Excel失败',
      error: error.message
    }
  }
} 